// src/hoverProvider.ts
import * as vscode from "vscode";
import { loadMark, parseMark } from "./codePaser";

class CTFHoverProvider implements vscode.HoverProvider {
  extensionUri;
  catalog: { [key: string]: string } | undefined;
  markPairs: { [key: string]: string } | undefined;
  constructor(extensionUri: vscode.Uri) {
    this.extensionUri = extensionUri;
    const markFilePath = vscode.Uri.joinPath(
      this.extensionUri,
      "resource",
      "Mark.md"
    );
    (async () => {
      try {
        const markFile = await loadMark(markFilePath);
        const { catalog, dictionary } = parseMark(markFile);
        this.catalog = catalog;
        this.markPairs = dictionary;
      } catch (err) {
        console.error(err);
      }
    })();
  }

  provideHover(
    document: vscode.TextDocument,
    position: vscode.Position,
    token: vscode.CancellationToken
  ): vscode.Hover | null {
    // read File
    try {
      // get KeyWord
      const wordRange = document.getWordRangeAtPosition(position);
      const word = document.getText(wordRange);
      if (!word) {
        return null;
      }
      // check Word 检查单词是否是我们想要提供提示信息的单词
      for (const regex in this.markPairs) {
        if (word.match(regex)) {
          const hoverMessage = new vscode.Hover(
            new vscode.MarkdownString(
              `\n\n **WebCTF** - **${regex}**\n\n${this.markPairs[regex]}  === `
            )
          );
          return hoverMessage;
        }
      }
    } catch (err) {
      console.error(`Error reading Mark.md\n ${err}`);
    }
    // ignore Word 如果不是我们关注的单词，返回null表示没有悬停提示
    return null;
  }
}

export default CTFHoverProvider;
